package cz.mpelant.msoe.mealchecker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;

import cz.mpelant.msoe.mealchecker.data.Plan;
import cz.mpelant.msoe.mealchecker.data.Plans;
import cz.mpelant.msoe.mealchecker.downloader.DownloadListener;
import cz.mpelant.msoe.mealchecker.downloader.DownloadRequest;
import cz.mpelant.msoe.mealchecker.downloader.DownloadResult;
import cz.mpelant.msoe.mealchecker.parser.OverviewParser;
import cz.mpelant.msoe.mealchecker.request.RequestLogin;

public class MainActivity extends BaseActivity {
	private static final String DOWNLOAD_OVERVIEW = "overview";
	private static final String FNAME_OVERVIEW = "overview.html";
	private static final int LOW_BALANCE = 5;
	private TextView txtSvc;
	private TextView txtMeals;
	private TextView txtRaider;

	private TextView txtSvcName;
	private TextView txtMealsName;
	private TextView txtRaiderName;

	private TextView txtUpdated;
	private Plans plans;

	private DownloadListener downloadListener = new DownloadListener() {

		@Override
		public void onDownloadStarted(DownloadRequest request, Context ctx) {
			Log.v("meal", "downloading " + request.getId() + " started");

		}

		@Override
		public void onProgressUpdate(DownloadResult progress, Context ctx) {
			Log.v("meal", "downloading " + progress.getRequest().getId() + ": " + progress.getProgress() + "%");

		}

		@Override
		public void onDownloadFinished(DownloadResult status, Context ctx) {

			if (status.getProgress() != DownloadResult.DOWNLOAD_FINISHED) {
				Log.w("meal", "download not finished, interrupting...");
				return;
			}
			Log.d("meal", status.getRequest().getId() + " finished with status code " + status.getHttpResponse().getStatusLine().getStatusCode());
			if (status.getRequest().getId().equals(DOWNLOAD_OVERVIEW)) {
				try {
					if (isLoginSuccessful(getCacheFile(FNAME_OVERVIEW))) {
						storeFileFromCache(FNAME_OVERVIEW);
						displayOverview(getInternalFile(FNAME_OVERVIEW));
					} else {
						Toast.makeText(MainActivity.this, R.string.error_login, Toast.LENGTH_SHORT).show();
					}
				} catch (IOException e) {
					Toast.makeText(MainActivity.this, R.string.error_io, Toast.LENGTH_SHORT).show();
				} catch (IllegalStateException e) {
					Toast.makeText(MainActivity.this, R.string.error_parse, Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}

			}

		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().setHomeButtonEnabled(false);
		setContentView(R.layout.main);
		
		plans = new Plans();

		txtSvc = (TextView) findViewById(R.id.svc);
		txtMeals = (TextView) findViewById(R.id.meals);
		txtRaider = (TextView) findViewById(R.id.raider);
		txtSvcName = (TextView) findViewById(R.id.svcName);
		txtMealsName = (TextView) findViewById(R.id.mealsName);
		txtRaiderName = (TextView) findViewById(R.id.raiderName);

		txtUpdated = (TextView) findViewById(R.id.updated);

		findViewById(R.id.llMeal).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startHistoryActivity(plans.meals);

			}
		});

		findViewById(R.id.llSVC).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startHistoryActivity(plans.svc);

			}
		});

		findViewById(R.id.llRaider).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startHistoryActivity(plans.raider);

			}
		});

		downloadOverview(false);
	}

	private void startHistoryActivity(Plan plan) {
		if (plan == null)
			return;
		Intent i = new Intent(MainActivity.this, HistoryActivity.class);
		i.putExtra(HistoryActivity.EXTRA_PLAN, plan);
		startActivity(i);
	}

	private void downloadOverview() {
		downloadOverview(true);

	}

	private void downloadOverview(boolean forced) {
		if (!forced && (!LoginActivity.isLoginInfo(this) || (System.currentTimeMillis() - getInternalFile(FNAME_OVERVIEW).lastModified() < MIN_TIME_BETWEEN_DOWNLOADS))) {
			return;
		}
		RequestLogin r = new RequestLogin(this);
		File f = getCacheFile(FNAME_OVERVIEW);
		try {
			downloader.download(new DownloadRequest(r.getHttpRequest(), new FileOutputStream(f), DOWNLOAD_OVERVIEW), downloadListener);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (LoginActivity.isLoginInfo(this)) {
			try {
				displayOverview(getInternalFile(FNAME_OVERVIEW));
			} catch (Exception e) {
				downloadOverview();
			}
		}

	}

	private boolean isLoginSuccessful(File f) throws FileNotFoundException {
		try {
			String data = OverviewParser.getData(readFileAsString(f));
			return data.contains("<th>Balance</th>");
		} catch (IOException e) {
			return false;
		}

	}

	private void setTextViewColor(TextView v) {
		v.setTextColor(getResources().getColor(R.color.green));
		try {
			String s = v.getText().toString();
			s = s.replace("$", "").trim();
			Double d = Double.parseDouble(s);
			if (d <= LOW_BALANCE)
				v.setTextColor(getResources().getColor(R.color.red));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void displayOverview(File f) throws IllegalStateException, IOException {
		if (isActivityActive == false)
			return;

		try {

			txtSvc.setTextColor(getResources().getColor(R.color.yellow));
			txtRaider.setTextColor(getResources().getColor(R.color.yellow));
			txtMeals.setTextColor(getResources().getColor(R.color.yellow));

			plans = OverviewParser.getPlans(readFileAsString(f));

			Log.v("meal", plans.svc.toString());
			Log.v("meal", plans.meals.toString());
			Log.v("meal", plans.raider.toString());

			txtSvc.setText(plans.svc.amount);
			txtRaider.setText(plans.raider.amount);
			txtMeals.setText(plans.meals.amount);

			txtSvcName.setText(plans.svc.name);
			txtRaiderName.setText(plans.raider.name);
			txtMealsName.setText(plans.meals.name);

			setTextViewColor(txtSvc);
			setTextViewColor(txtMeals);
			setTextViewColor(txtRaider);

			txtUpdated.setText(new Date(f.lastModified()).toLocaleString());

		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}

	}

	@Override
	public void onBackPressed() {
		downloader.cancelDownloads();
		super.onBackPressed();
	}

	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			MenuItem menuItem;
			menuItem = menu.add(R.string.history);
			menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
				@Override
				public boolean onMenuItemClick(MenuItem item) {
					startHistoryActivity(plans.all);
					return true;
				}
			});
			
			return super.onCreateOptionsMenu(menu);
		}
	 @Override
	protected void refresh() {
		downloadOverview();
	}

	
}